package com.example.springboot01.el;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

import java.io.IOException;

/**
 * @author keyer
 * @Description : 配置类，用于扫描bean
 * 1.注入配置文件需要使用 @PropertySource ，定位配置文件；
 * 2.若使用@value注入，则需要配置一个PropertySourcesPlaceholderConfigurer的bean
 * 3.注意表达式用# ，直接引用的用$
 * <p>
 * Created by cyd on 2021-04-30 15:24:45
 */
@Configuration
@ComponentScan("com.example.springboot01.el")
@PropertySource("classpath:com/example/springboot01/el/test.properties")
public class ElConfig {

    /**
     * 注入普通字符串
     */
    @Value("i love you")
    private String normal;

    /**
     * 注入系统属性
     */
    @Value("#{systemProperties['os.name']}")
    private String osName;

    /**
     * 注入表达式结果
     */
    @Value("#{T(java.lang.Math).random()*100.0}")
    private double randomNumber;

    /**
     * 注入文件资源
     */
    @Value("classpath:com/example/springboot01/el/test.txt")
    private Resource testFile;

    /**
     * 注入网址资源
     */
    @Value("http://www.baidu.com")
    private Resource testUrl;

    /**
     * 注入其他bean的属性
     */
    @Value("#{demoService.anOther}")
    private String fromAnOther;

    /**
     * 注入配置文件中的配置
     */
    @Value("${book.name}")
    private String bookName;

    /**
     * 注入配置文件中的配置
     */
    @Value("${temp}")
    private String temp;

    /**
     * 配置文件中的属性，还可以从environment中获取
     */
    @Autowired
    private Environment environment;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
        return new PropertySourcesPlaceholderConfigurer();
    }


    public void outPutResources() throws IOException {
        System.out.println(normal);
        System.out.println(osName);
        System.out.println(randomNumber);
        System.out.println(fromAnOther);
        System.out.println(temp);
        System.out.println(IOUtils.toString(testFile.getInputStream()));
        System.out.println(IOUtils.toString(testUrl.getInputStream()));
        System.out.println(bookName);
        System.out.println(environment.getProperty("book.author"));
    }
}
